package com.shupian.controller;

import com.shupian.domain.ResponseResult;
import com.shupian.domain.dto.LoginUserDTO;
import com.shupian.domain.entity.LoginUser;
import com.shupian.domain.entity.Menu;
import com.shupian.domain.entity.User;
import com.shupian.domain.vo.AdminUserInfoVo;
import com.shupian.domain.vo.RoutersVo;
import com.shupian.domain.vo.UserInfoVo;
import com.shupian.enums.AppHttpCodeEnum;
import com.shupian.exception.SystemException;
import com.shupian.service.LoginService;
import com.shupian.service.MenuService;
import com.shupian.service.RoleService;
import com.shupian.service.UserService;
import com.shupian.utils.BeanCopyUtils;
import com.shupian.utils.RedisCache;
import com.shupian.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import java.util.List;

@RestController
public class LoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private RoleService roleService;

    @Autowired
    private UserService userService;

    @PostMapping("/user/login")
    public ResponseResult login(@RequestBody @Valid  LoginUserDTO loginUserDTO) {
        User user = BeanCopyUtils.copyBean(loginUserDTO, User.class);
        if (!StringUtils.hasLength(user.getUserName())) {
            //提示 必须要传用户名
            throw new SystemException(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
        return loginService.login(user);
    }

    @GetMapping("/getInfo")
    public ResponseResult<AdminUserInfoVo> getInfo(){
      //获取当前登录的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
      //根据用户id查询权限信息
      List<String> perms =   menuService.selectPermsByUserId(loginUser.getUser().getId());
      // 根据用户id查询角色信息
        List<String> roleKeyList = roleService.selectRoleKeyByUserId(loginUser.getUser().getId());
        //获取用户信息
        User user =  loginUser.getUser();
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(user, UserInfoVo.class);
        //封装返回

        AdminUserInfoVo adminUserInfoVo = new AdminUserInfoVo(perms,roleKeyList,userInfoVo);
        return ResponseResult.okResult(adminUserInfoVo);
    }

    @GetMapping("/getRouters")
    public ResponseResult<RoutersVo> getRouters() {
        //获取当前登录的用户
        Long userId = SecurityUtils.getUserId();
        //查询menu 结果是tree的形式
        List<Menu> meus = menuService.selectRoleKeyByUserId(userId);
        //封装返回
        return ResponseResult.okResult(new RoutersVo(meus));
    }

    @PostMapping("/user/logout")
    public ResponseResult logout() {

        return loginService.logout();
    }

}
